package com.sdgakj.service.order;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.sdgakj.dto.CreateOrderDTO;
import com.sdgakj.dto.OrderDTO;
import com.sdgakj.dto.base.ResCode;
import com.sdgakj.entity.Order;
import com.sdgakj.entity.OrderPay;
import com.sdgakj.entity.User;
import com.sdgakj.enums.EnumIsPay;
import com.sdgakj.enums.EnumOrderStatus;
import com.sdgakj.repository.OrderDao;
import com.sdgakj.repository.OrderPayDao;
import com.sdgakj.repository.UserDao;
import com.sdgakj.service.ServiceException;
import com.sdgakj.service.user.UserService;
import com.sdgakj.utils.SchoolSearchFilter;
import com.sdgakj.utils.SchoolSpecifications;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.mapper.BeanMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.*;

@Component
@Transactional
public class OrderService {

    private static Logger logger = LoggerFactory.getLogger(OrderService.class);

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderPayDao orderPayDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserService userService;

    public List<Order> getAllList() {
        return (List<Order>) orderDao.findAll();
    }

    public Order getOrderById(Long id) {
        return orderDao.findOne(id);
    }

    public Order getOrderByGpsService(Long id) {
        return orderDao.findByService(id);
    }

    /**
     * 保存
     * 
     * @param entity
     */

    public Order saveOrder(Order entity) {
        Timestamp tsc = new Timestamp(new Date().getTime());
        entity.setCreatetime(tsc);
        return orderDao.save(entity);
    }


    /**
     * 保存
     */
    public CreateOrderDTO create(Long userId,
                                 String authTel,
                                 Double totalPrice,
                                 Integer realNum,
                                 Integer targetNum) {
        CreateOrderDTO result = new CreateOrderDTO();
        if (0l == userId) {
            throw new ServiceException(ResCode.NEED_USERID);
        }
        Order order = new Order();
        order.setUserId(userId);
        order.setAuthTel(authTel);
        order.setState(EnumOrderStatus.DELETE.getCode());
        order.setAmount(totalPrice);
        order.setRealNum(realNum);
        order.setTargetNum(targetNum);
        Order newOrder = this.saveOrder(order);
        result.setCreateTime(newOrder.getCreatetime().getTime());
        result.setOrderId(newOrder.getId());
        return result;
    }
    /*
    * 创建订单
    * */
    public Order insertOrder(Long userId){
        Order order = new Order();
        User user = new User();
        order.setUserId(userId);
        order.setAuthTel(user.getMobile());
        order.setState(0);
        orderDao.save(order);
       return orderDao.findOne(userId);
    }
    /**
     * 更新
     * 
     * @param entity
     */
    public void updateOrder(Order entity) {

        entity.setUpdatetime(new Date());

        orderDao.save(entity);
    }


    public Page<Order> getOrderByPage(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortName, String sortType) {
        PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize, Sort.Direction.DESC, "id");
        searchParams.put("NOTEQ_state", 0);
        Map<String, SchoolSearchFilter> filters = SchoolSearchFilter.parse(searchParams);
        Specification<Order> spec = SchoolSpecifications.bySearchFilter(filters.values(), Order.class);
        return orderDao.findAll(spec, pageRequest);
    }

    /*
     * 获取我的订单 赵哲
     */
    public List<OrderDTO> getOrderByUserId(Long customorId, Integer type, Integer state) {
        Map<String, Object> searchParams = new HashMap<String, Object>();
        searchParams.put("EQ_customor.id", customorId);
        searchParams.put("EQ_type", type);
        searchParams.put("EQ_state", state);
        Specification<Order> spec = buildSpecification(searchParams);
        Sort sort = new Sort(Direction.DESC, "id");
        List<Order> orders = orderDao.findAll(spec, sort);
        List<OrderDTO> orderDTOs = new ArrayList<OrderDTO>();
        for (Order order : orders) {
            closeNeedCloseOrder(order);
            if (!EnumOrderStatus.NEEDPAY.getCode().equals(order.getState())) {
                continue;
            }
            OrderDTO orderDTO = BeanMapper.map(order, OrderDTO.class);
            orderDTOs.add(orderDTO);
        }
        for (Order order : orders) {
            if (EnumOrderStatus.NEEDPAY.getCode().equals(order.getState())) {
                continue;
            }
            OrderDTO orderDTO = BeanMapper.map(order, OrderDTO.class);

            orderDTOs.add(orderDTO);
        }
        return orderDTOs;
    }

    /*
     * 获取待打款订单 赵哲
     */
    public Map<String, Object> payedBillNotify(String jsonData) throws JSONException {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String resMsg = "请求成功";
        if (StringUtils.isBlank(jsonData)) {
            resMsg = "数据传输错误";
            resultMap.put("resMsg", resMsg);
            resultMap.put("resCode", "0");
            return resultMap;
        }

        org.json.JSONObject jsonObject = new org.json.JSONObject(jsonData);
        int resCode = jsonObject.getInt("resCode");
        if (resCode != 1) {
            resultMap.put("resMsg", "请求不正确");
            resultMap.put("resCode", "0");
            return resultMap;
        }


        org.json.JSONArray jsonArray = jsonObject.getJSONArray("data");
        int iSize = jsonArray.length();
        for (int i = 0; i < iSize; i++) {
            org.json.JSONObject jsonObj = jsonArray.getJSONObject(i);
            String id = String.valueOf(jsonObj.get("id"));
            String amount = String.valueOf(jsonObj.get("amount"));
            String state = String.valueOf(jsonObj.get("state"));
            String errMsg = String.valueOf(jsonObj.get("errMsg"));
        } //end for
        return resultMap;
    }

    
    // 订单支付返回结果
    public String orderPayResultNotify(HttpServletRequest request, HttpServletResponse response,
            Map<String, Object> body, Integer payType) {

        String tradeStatus = (String) body.get("trade_status");
        String tradeNo = (String) body.get("trade_no");
        Long orderId = Long.valueOf((String) body.get("out_order_id"));
        String account = (String) body.get("account");
        Order order = this.getOrderById(orderId);

        Preconditions.checkNotNull(order,"订单Id为空orderId=" + orderId);

        JSONObject json = new JSONObject();
        if ("TRADE_FAIL".equals(tradeStatus)) {
            // 支付失败
            json.put("resCode", ResCode.PAY_ORDER_FAILED.resCode);
            json.put("resMsg", ResCode.PAY_ORDER_FAILED.resMsg);
        }
        if ("TRADE_SUCCESS".equals(tradeStatus)) {
            if (2 == order.getIsPay()) {
                json.put("resCode", ResCode.PAY_ORDER_ALREADYPAY.resCode);
                json.put("resMsg", ResCode.PAY_ORDER_ALREADYPAY.resMsg);
                return json.toJSONString();
            }

            try {

                // 标志已经支付
                OrderPay orderPay = new OrderPay();
                //start--2016年7月29日14:55:29 李贺刚
                    logger.info(order.getId() + "payType:" + payType + "account:" + account + "tradeNo:" + tradeNo);
                //end--
                orderPay.setType(payType);
                orderPay.setAccount(account);
                orderPay.setTransactionNo(tradeNo);
                orderPay.setState(EnumIsPay.IsPay.getCode());
                orderPay.setState(1);
                orderPay.setPayTime(new Date());
                OrderPay newOrderPay = orderPayDao.save(orderPay);

                order.setOrderPay(newOrderPay);
                this.updateOrder(order);
                json.put("resCode", "0");
                json.put("resMsg", "订单支付成功");
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }
        }

        return json.toJSONString();
    }

    // 订单支付返回结果
    public void closeNeedCloseOrder(Order order) {
        long currentTime = System.currentTimeMillis();
        // 在这个基础上减去24小时：
        Long courseCancelTime = currentTime - 24 * 60 * 60 * 1000;
        // 格式化时间，获取到的就是当前时间24小时之后的时间
        Date courseCancelDate = new Date(courseCancelTime);
        if (order.getState().equals(EnumOrderStatus.NEEDPAY.getCode())
                && order.getCreatetime().before(courseCancelDate)) {
            // 订单创建时间在24小时之前，修改订单状态
            order.setState(EnumOrderStatus.CLOSED.getCode());
            this.updateOrder(order);
        }
    }

    /*
     * 订单取消退款
     */
    public void unrefundOrder(Long orderId) {
        Order order = this.getOrderById(orderId);
        order.setState(EnumOrderStatus.ISPAY.getCode());
        try {
            this.updateOrder(order);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /*
     * 订单取消
     */
    public void cancelOrder(Long orderId) {
        Order order = this.getOrderById(orderId);
        order.setState(EnumOrderStatus.CLOSED.getCode());

        try {
            this.updateOrder(order);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /*
     * 订单删除
     */
    public void deleteOrder(Long orderId) {
        Order order = this.getOrderById(orderId);
        order.setState(EnumOrderStatus.DELETE.getCode());

        try {
            this.updateOrder(order);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /*
     * 获取订单价格
     */
    public Double getOrderPrice(Long orderId) {
        Order order = this.getOrderById(orderId);
        return order.getAmount();
    }

    /*
     * 订单投诉
     */
    public void complainOrder(Long orderId, String reason) {
        // Order order = this.getOrderById(orderId);

    }

    /**
     * 创建分页请求.
     */
    private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
        Sort sort = null;
        if ("auto".equals(sortType)) {
            sort = new Sort(Direction.DESC, "id");
        }
        return new PageRequest(pageNumber - 1, pagzSize, sort);
    }

    /**
     * 创建动态查询条件组合.
     */
    private Specification<Order> buildSpecification(Map<String, Object> searchParams) {
        Map<String, SchoolSearchFilter> filters = SchoolSearchFilter.parse(searchParams);
        Specification<Order> spec = SchoolSpecifications.bySearchFilter(filters.values(), Order.class);
        return spec;
    }

	public int getCountByWait() {
		
		return orderDao.getCountByWait();
	}
	
}
